import 'dart:async';

import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';
import 'package:x3_business_core/business_common_template/components/business_detailed_main_order.dart';
import 'package:x3_business_core/business_common_template/enum/business_order_type.dart';
import 'package:x3_business_core/business_common_template/models/business_detailed_order_service.dart';
import 'package:x3_business_core/business_common_template/service/business_detailed_order_provider.dart';
import 'package:x3_business_core/common_components/business_tab_nested_scroll_view.dart';

/// 作者：william on 2021/3/11 14:53
/// 邮箱：362661044@qq.com

/// 通用业务单详情
class BusinessDetailedOrderPage extends StatefulWidget {
  final BusinessOrderType orderType;
  final BusinessDetailedOrderService service;
  final BaseRequestFormProvider baseRequestFormProvider;
  final bool isPopReload;

  // 新建/编辑 页面是否显示保存按钮
  final bool showSaveButton;

  const BusinessDetailedOrderPage({Key key, @required this.baseRequestFormProvider, @required this.service, this.orderType = BusinessOrderType.create, this.isPopReload = false, this.showSaveButton = true}) : super(key: key);

  @override
  _BusinessDetailedOrderPageState createState() => _BusinessDetailedOrderPageState();
}

class _BusinessDetailedOrderPageState extends State<BusinessDetailedOrderPage> with BusinessDetailedOrder {
  @override
  Widget build(BuildContext context) {
    return buildContent();
  }

  @override
  BaseRequestFormProvider get formProvider => widget.baseRequestFormProvider;

  @override
  bool get isPopReload => widget.isPopReload;

  @override
  BusinessOrderType get orderType => widget.orderType;

  @override
  BusinessDetailedOrderService get service => widget.service;

  @override
  bool get showSaveButton => widget.showSaveButton;
}

mixin BusinessDetailedOrder<T extends StatefulWidget> on State<T> {
  final StreamController<BusinessDetailedOrderTab> _refreshTabStream = StreamController<BusinessDetailedOrderTab>.broadcast();

  /// 服务地址
  BusinessDetailedOrderService get service;

  /// 是否退出 刷新
  bool get isPopReload;

  /// 表单控制器
  BaseRequestFormProvider get formProvider;

  /// 主单状态
  BusinessOrderType get orderType;

  bool changedFormState = false;

  StateSetter _saveButSetter;

  /// 显示保存按钮
  bool get showSaveButton;

  @override
  void initState() {
    formProvider.onChangeListener((request, data) {
      if (_saveButSetter != null)
        _saveButSetter(() {
          changedFormState = true;
        });
    });
    super.initState();
  }

  Widget buildContent() {
    return BaseScaffoldComponent(
      title: _buildBillsName(),
      footerWidget: _buildFooterWidget(),
      willPopScope: () {
        Navigator.of(context).pop(isPopReload);
        return Future.value(false);
      },
      child: BaseScreenRefreshComponent(
        // 查询主单
        request: BaseScreenRequestModel(service.queryMainService.path, method: BaseHttpMethodEnum.GET, params: (service.userType != null && service.userType.isEmpty) ? service.billsIdMap : {...service.billsIdMap, 'userType': service.userType}),
        builder: (BaseHttpResultModel result) {
          if (result.success == true) {
            /// 获取主单值
            formProvider.dataSource.addAll(result.data);
            return Provider(
              create: (_) => BusinessDetailedOrderProvider(refreshTabStream: _refreshTabStream, service: service, baseRequestFormProvider: formProvider),
              child: _buildContent(),
            );
          }
          return BaseEmptyComponent();
        },
      ),
    );
  }

  String _buildBillsName() {
    switch (orderType) {
      case BusinessOrderType.create:
        return '新建' + service.billsName;
      case BusinessOrderType.edit:
        return '编辑' + service.billsName;
    }
    return '';
  }

  Widget _buildContent() {
    return BusinessTabNestedScrollView(
      headerWidget: BusinessDetailedMainOrder(billsId: service.billsId, baseRequestFormProvider: formProvider),
      tabs: service.tabs,
    );
  }

  /// 底部按钮
  Widget _buildFooterWidget() {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          Expanded(child: BaseButton.bottom(text: '删除', fill: false, onPress: _onDel)),
          if (!showSaveButton) SizedBox(width: 12.0),
          if (showSaveButton) SizedBox(width: 8),
          if (showSaveButton)
            Expanded(child: StatefulBuilder(
              builder: (context, _state) {
                _saveButSetter = _state;
                return BaseButton.bottom(text: '保存', disable: !changedFormState, onPress: changedFormState == false ? null : _onSave, fill: false);
              },
            )),
          if (showSaveButton) SizedBox(width: 8),
          Expanded(child: BaseButton.bottom(text: '提交', onPress: _onSure, fill: false)),
        ],
      ),
    );
  }

  /// 删除主单
  void _onDel() async {
    BaseComponentUtils.showMessageDialog(context, content: '你真的要删除吗?', onOKPress: () async {
      BaseComponentUtils.showLoadingDialog(context);
      BaseHttpResultModel result = await dioUtil.fetch(service.delMainService.path, method: service.delMainService.method, params: service.billsIdMap);
      BaseComponentUtils.hideLoadingDialog(context);
      if (result.success == true) {
        /// 关闭弹窗
        Navigator.pop(context);
        BaseRouterUtil().pop(true);
      }
    });
  }

  /// 更新保存主单
  void _onSave() async {
    Map<String, dynamic> groupTypeMap = {};
    if (service.groupType != null && service.groupType != "-2") {
      groupTypeMap.addAll({'groupType': service.groupType});
    }
    BaseComponentUtils.showLoadingDialog(context);
    BaseHttpResultModel result = await dioUtil.fetch(service.saveMainService.path, method: BaseHttpMethodEnum.PUT, params: {
      ...service.billsIdMap,
      ...formProvider.getAllDataMapKey(),
      ...groupTypeMap,
    });
    BaseComponentUtils.hideLoadingDialog(context);
    if (result.success == true) {
      if (_saveButSetter != null)
        _saveButSetter(() {
          changedFormState = false;
        });
      BaseUtils.showToast('保存成功');
    }
  }

  /// 提交主单
  void _onSure() {
    String tips = changedFormState == true ? '主单有改动，是否继续提交?' : '是否提交?';

    /// 检查截止日期
    DateTime now = DateTime.now();
    DateTime _endDate = DateTime.tryParse(formProvider.fieldNameToDataSource('endDate')).toLocal().add(Duration(days: 1));

    /// 当前时间大于 结束时间
    if (now.isBefore(_endDate) == false) {
      BaseUtils.showToast('截止日期必须大于现在时间');
      return;
    }
    BaseComponentUtils.showMessageDialog(context, content: tips, onOKPress: () async {
      BaseComponentUtils.showLoadingDialog(context);
      BaseHttpResultModel result = await dioUtil.fetch(service.sureMainService.path, method: service.sureMainService.method, params: service.billsIdMap);
      BaseComponentUtils.hideLoadingDialog(context);
      if (result.success == true) {
        Navigator.pop(context);
        BaseRouterUtil().pop(true);
      }
    });
  }

  /// 注意重写这个的话 要关闭流
  @override
  void dispose() {
    _refreshTabStream.close();
    super.dispose();
  }
}
